package top.lyc829.zzl_android.ui.thing.dynamic_detail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.button.shinebutton.ShineButton;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.imageview.nine.NineGridImageView;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.statelayout.MultipleStatusView;
import com.xuexiang.xutil.data.DateUtils;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityBaseDetailBinding;
import top.lyc829.zzl_android.databinding.ActivityDynamicDetailBinding;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.bean.ImageViewInfo;
import top.lyc829.zzl_android.logic.bean.LiveEventMsg;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.ShareBean;
import top.lyc829.zzl_android.logic.bean.SonCommentBean;
import top.lyc829.zzl_android.logic.bean.SuperCommentBean;
import top.lyc829.zzl_android.logic.bean.TravelDetailBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.base_detail.CommentsAdapter;
import top.lyc829.zzl_android.ui.base_detail.SonCommentsAdapter;
import top.lyc829.zzl_android.ui.custom_view.InputTextMsgDialog;
import top.lyc829.zzl_android.ui.custom_view.ShareMsgDialog;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

public class DynamicDetailActivity extends AppCompatActivity {

    private DynamicDetailViewModel mViewModel;
    private int dynamicId, position;
    private ActivityDynamicDetailBinding binding;
    CommentsAdapter adapter;
    SonCommentsAdapter sonAdapter;
    PageInfo superCommentsPage,sonPageInfo;

    ShareMsgDialog shareMsgDialog;

    private int replayType = ReplayType.OTHER; // 回复类型，0 - 基地 1 - 评论
    private int commendedId = -1;    // 被评论的评论的id

    private int commentedUserId = -1;

    private NineGridImageView<String> dynamicDetailNglImages;
    private NineGridAdapter nineGridAdapter;

    InputTextMsgDialog inputTextMsgDialog;
    MaterialDialog loadingDialog;
    BottomSheetDialog dialog;
    BottomSheetDialog deleteDialog;

    MiniLoadingDialog mMiniLoadingDialog;

    int type = -1;

    // 是否需要滚动到底部评论
    boolean isNeedComment = false;

    private Handler mLoadingHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDynamicDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        dynamicDetailNglImages = findViewById(R.id.dynamic_detail_ngl_images);
        // 实例化加载框
        loadingDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_loading_layout, true)
                .cancelable(false)
                .build();

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);
        mMiniLoadingDialog.show();

        binding.mTitleBarDynamicDetail.setLeftClickListener(v -> finish());

        type = getIntent().getIntExtra("type", -1);
        dynamicId = getIntent().getIntExtra("id", -1);
        position = getIntent().getIntExtra("position", -1);
        isNeedComment = getIntent().getBooleanExtra("is_comment", false);
        mViewModel = new ViewModelProvider(this).get(DynamicDetailViewModel.class);
        superCommentsPage = new PageInfo();
        sonPageInfo = new PageInfo();

        mLoadingHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mMiniLoadingDialog.isLoading()) {
                    mMiniLoadingDialog.dismiss();
                    Utils.showToast("加载失败");
                    finish();
                }
            }
        }, 8000);

        observe();
        initCommentAdapter();
        initNineGridAdapter();
        initCommentDialog();
        initLoadMore();
        clickListener();
        initData();

    }

    /**
     * 弹出底部删除弹窗
     */
    private void showBottomDialog() {
        if (deleteDialog == null) {
            deleteDialog = new BottomSheetDialog(this, R.style.MyBottomSheetDialog);
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog_dynamic_long_click, null);

            view.findViewById(R.id.dynamic_long_delete).setOnClickListener(v -> {
                deleteComment();
                deleteDialog.dismiss();
            });

            view.findViewById(R.id.dynamic_long_cancel).setOnClickListener(v -> {
                deleteDialog.dismiss();
            });

            deleteDialog.setContentView(view);
            deleteDialog.setCancelable(true);
            deleteDialog.setCanceledOnTouchOutside(true);
        }
        deleteDialog.show();

    }

    /**
     * 删除评论
     */
    private void deleteComment() {
        if (mViewModel.getCommentDeleteLiveData().getValue() == null) {
            return;
        }
        Pair<Integer, Integer> commentPair = mViewModel.getCommentDeleteLiveData().getValue();

        int commentId;
        if (commentPair.first.equals(1)) {
            commentId = adapter.getItem(commentPair.second).getCommentId();
        } else {
            commentId = sonAdapter.getItem(commentPair.second).getCommentId();
        }
        Network.deleteComment(Utils.getUserId(), commentId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        Utils.showToast("删除成功");
                        if (commentPair.first.equals(1)) {
                            adapter.removeAt(commentPair.second);
                            int num = Integer.parseInt(binding.dynamicDetailReplayNum.getText().toString());
                            binding.dynamicDetailReplayNum.setText(String.valueOf(num - 1));
                            sendCommentsEvent(num - 1);
                        } else {
                            sonAdapter.removeAt(commentPair.second);

                            if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, -1);
                                mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                            }

                        }
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    // 点击事件监听
    private void clickListener() {
        dynamicDetailNglImages.setItemImageClickListener((imageView, index, list) -> {

            ImageView currentView = (ImageView)  dynamicDetailNglImages.getChildAt(index);
            if (currentView.getTag() == null || !currentView.getTag().equals("load_success")) {
                Utils.Sout("图片加载中");
                return;
            }

            List<ImageViewInfo> res = computeBoundsBackward(list);//组成数据
            PreviewBuilder.from((Activity) imageView.getContext())
                    .setImgs(res)
                    .setCurrentIndex(index)
                    .setProgressColor(R.color.zzl_red)
                    .setType(PreviewBuilder.IndicatorType.Dot)
                    .start();//启动
        });

        binding.dynamicDetailPraise.setOnClickListener(v -> {

            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
                return;
            }

            binding.dynamicDetailPraise.setClickable(false);
            if (mViewModel.getIsPraiseLiveData().getValue() != null) {
                mMiniLoadingDialog.show();
                int isLike = mViewModel.getIsPraiseLiveData().getValue();
                if (isLike == 0) {
                    Network.sendLike(Utils.getUserId(), ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    binding.dynamicDetailPraise.setClickable(true);
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsPraiseLiveData().postValue(1);
                                    binding.dynamicDetailPraiseNum.setText(String.valueOf(Integer.parseInt(binding.dynamicDetailPraiseNum.getText().toString()) + 1));
                                    //DynamicBean dynamic = mViewModel.getDynamicBeanLiveData().getValue();
                                    //dynamic.setLikes(dynamic.getLikes() + 1);
                                    //mViewModel.getDynamicBeanLiveData().postValue(dynamic);
                                });

                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                binding.dynamicDetailPraise.setClickable(true);
                                mMiniLoadingDialog.dismiss();
                                Utils.SoutErr(e.getMessage());
                            });

                        }
                    });
                } else {
                    Network.sendUnLike(Utils.getUserId(), ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
//                                mViewModel.getIsPraiseLiveData().postValue(0);
//                                DynamicBean dynamic = mViewModel.getDynamicBeanLiveData().getValue();
//                                dynamic.setLikes(dynamic.getLikes() - 1);
//                                mViewModel.getDynamicBeanLiveData().postValue(dynamic);
                                runOnUiThread(() -> {
                                    binding.dynamicDetailPraise.setClickable(true);
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsPraiseLiveData().postValue(0);
                                    binding.dynamicDetailPraiseNum.setText(String.valueOf(Integer.parseInt(binding.dynamicDetailPraiseNum.getText().toString()) - 1));
                                });
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                binding.dynamicDetailPraise.setClickable(true);
                                mMiniLoadingDialog.dismiss();
                                Utils.SoutErr(e.getMessage());
                            });
                        }
                    });
                }
            }
        });


        binding.dynamicBottomComment.setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.DYNAMIC;
            commendedId = dynamicId;
        });

        adapter.addChildClickViewIds(R.id.comment_item_like_btn, R.id.comment_item_go_replay, R.id.comment_item_avatar);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;    // 回复评论
            commendedId = ((SuperCommentBean) adapter.getData().get(position)).getCommentId();
            commentedUserId = ((SuperCommentBean) adapter.getData().get(position)).getUseId();
        });
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter1, @NonNull View view, int position) {
                if (view.getId() == R.id.comment_item_go_replay) {

                    mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(position, Integer.MIN_VALUE));

                    // 弹出BottomSheetDialog, 显示评论评论的评论
                    sonPageInfo.reset();
                    showBottomSheetListDialog((SuperCommentBean) adapter.getData().get(position));
                    mViewModel.getSonComments(((SuperCommentBean) adapter.getData().get(position)).getCommentId(), sonPageInfo.getPage());
                } else if (view.getId() == R.id.comment_item_like_btn) {
                    if (!Utils.isLogin()) {
                        Utils.showToast("请先登录");
                        return;
                    }

                    View itemView = binding.dynamicCommentsRecyclerview.getLayoutManager().findViewByPosition(position);
                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(false);
                    //ShineButton shineButton = (ShineButton) view;
                    SuperCommentBean superComment = adapter.getItem(position);
                    //未点赞，点赞请求
                    if (superComment.getIsLike().equals(0)) {
                        Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.dynamicCommentsRecyclerview.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(1);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() + 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.dynamicCommentsRecyclerview.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });

                            }
                        });
                    } else {
                        Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.dynamicCommentsRecyclerview.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(0);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() - 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.dynamicCommentsRecyclerview.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });
                            }
                        });
                    }

                } else if (view.getId() == R.id.comment_item_avatar) {
                    Intent intent = new Intent(DynamicDetailActivity.this, OtherUserDetailActivity.class);
                    intent.putExtra("id", adapter.getItem(position).getUseId());
                    startActivity(intent);
                }
            }
        });

        // 一级评论长按删除监听
        adapter.setOnItemLongClickListener((adapter1, view, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!adapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(1, position));
            showBottomDialog();

            return false;
        });


        binding.dynamicDetailShare.setOnClickListener(v -> {
            shareToDynamic();
        });

        binding.dynamicDetailComment.setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.DYNAMIC;
            commendedId = dynamicId;
        });


        binding.dynamicDetailAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(this, OtherUserDetailActivity.class);
            intent.putExtra("id", mViewModel.getDynamicBeanLiveData().getValue().getUserId());
            startActivity(intent);
        });

        // 监听关注按钮
        binding.dynamicDetailFollow.setOnClickListener(v -> {
            if (!Utils.isLogin()) { // 保证用户登陆之后才能继续操作
                Utils.showToast("请先登录");
                Utils.goLogin(this);
            } else if (mViewModel.getIsFellowLiveData().getValue() != null) {
                mMiniLoadingDialog.show();
                if(mViewModel.getIsFellowLiveData().getValue().equals(0)) {
                    Network.attention(Utils.getUserId(), FellowType.USER, mViewModel.getDynamicBeanLiveData().getValue().getUserId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                // 重新获取点赞关系
                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsFellowLiveData().setValue(1);
                                });

                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("关注失败");
                            });


                        }
                    });

                } else if (mViewModel.getIsFellowLiveData().getValue().equals(1)) {
                    Network.unAttention(Utils.getUserId(), FellowType.USER, mViewModel.getDynamicBeanLiveData().getValue().getUserId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                // 重新获取点赞关系
                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsFellowLiveData().setValue(0);
                                });

                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("取消关注失败");
                            });
                        }
                    });

                }
            }


        });

        binding.editShare.setOnClickListener(v -> {
            goOriginDynamic();
        });

    }

    // 去原始动态
    private void goOriginDynamic() {
        DynamicBean item = mViewModel.getDynamicBeanLiveData().getValue();
        Intent intent = null;
        if (item.getType().equals(DynamicType.BASE)) {
            intent  = new Intent(this, BaseDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        } else if (item.getType().equals(DynamicType.DYNAMIC)) {
            intent  = new Intent(this, DynamicDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        }else if (item.getType().equals(DynamicType.TRAVEL)) {
            intent  = new Intent(this, TravelDetailActivity.class);
            intent.putExtra("travel_id", item.getTypeId());
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void shareToDynamic() {
        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            return;
        }
        if (shareMsgDialog == null) {
            DynamicBean dynamic = mViewModel.getDynamicBeanLiveData().getValue();

            shareMsgDialog = new ShareMsgDialog(
                    DynamicDetailActivity.this,
                    R.style.dialog_center,
                    new ShareBean(dynamic.getUserName(), dynamic.getDynamicText() ,dynamic.getDynamicUrl().get(0)));
            shareMsgDialog.setmOnTextSendListener(msg -> {
                shareMsgDialog.dismiss();
                loadingDialog.show();

                Network.shareToDynamic(DynamicType.DYNAMIC, dynamic.getDynamicId(), Utils.getUserId(),msg, new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resStr = res.body().string();
                        ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                        if (resultBean.getCode().equals(200)) {
                            runOnUiThread(() ->{
                                loadingDialog.dismiss();
                                Utils.showToast("分享成功");
                            });
                        } else {
                            failed(new IOException(resultBean.getMsg()));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        runOnUiThread(() -> {
                            Utils.Sout(e.getMessage());
                            loadingDialog.dismiss();
                        });

                    }
                });

            });

        }

        shareMsgDialog.show();
    }


    private void sendLiveEvent(int isLike) {

        Utils.Sout("----------发送点赞消息");

        Map<String, String> map = new HashMap<>();
        map.put("position", String.valueOf(position));
        map.put("is_like", String.valueOf(isLike));


        if (type == 0) {
            LiveEventBus
                    .get("dynamic_praise_dynamic")
                    .post(new LiveEventMsg(map));
        } else if (type == 1) {
            LiveEventBus
                    .get("dynamic_praise_follow")
                    .post(new LiveEventMsg(map));
        }
    }

    private void sendCommentsEvent(int num) {

        Utils.Sout("----------发送评论消息");

        Map<String, String> map = new HashMap<>();
        map.put("position", String.valueOf(position));
        map.put("comments", String.valueOf(num));

        if (type == 0) {
            LiveEventBus
                    .get("dynamic_comment_dynamic")
                    .post(new LiveEventMsg(map));
        } else if (type == 1) {
            LiveEventBus
                    .get("dynamic_comment_follow")
                    .post(new LiveEventMsg(map));
        }
    }

    /**
     * 弹出底部评论弹窗
     */
    private void showCommentDialog() {

        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            Intent intent = new Intent(DynamicDetailActivity.this, LoginActivity.class);
            startActivity(intent);
        } else {
            inputTextMsgDialog.show();
        }
    }

    /**
     * 初始化底部评论弹窗
     */
    private void initCommentDialog() {
        if(inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog_center);
            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String msg) {
                    inputTextMsgDialog.dismiss();

                    loadingDialog.show();


                    Network.sendComments(Integer.parseInt(Utils.getValueFromSp("user_id")),
                            replayType, commendedId, msg, commentedUserId, new HttpUtil.MyCallback() {
                                @Override
                                public void success(Response res) throws IOException {
                                    String resultStr = res.body().string();
                                    ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                                    if (resultBean.getCode().equals(200)) {
                                        loadingDialog.dismiss();

                                        runOnUiThread(() -> {
                                            if (replayType == ReplayType.DYNAMIC) {
                                                int num = Integer.parseInt(binding.dynamicDetailReplayNum.getText().toString()) + 1;
                                                binding.dynamicDetailReplayNum.setText(String.valueOf(num));
                                                sendCommentsEvent(num);
                                            }
                                            // 子评论界面没有加载，则刷新一级评论，否则刷新N级评论
                                            if (dialog == null || !dialog.isShowing()) {
                                                superCommentsPage.reset();
                                                // 重新获取以及评论
                                                mViewModel.getSuperComments(ReplayType.DYNAMIC, dynamicId, superCommentsPage.getPage());

                                            } else {
                                                sonPageInfo.reset();
                                                // 重新获取子评论
                                                mViewModel.getSonComments(commendedId, sonPageInfo.getPage());

                                                if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                                    Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, 1);
                                                    mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                                                }

                                            }
                                        });






                                    } else {
                                        failed(new IOException());
                                    }

                                }

                                @Override
                                public void failed(IOException e) {
                                    loadingDialog.dismiss();
                                    Utils.showToastSync("评论失败");
                                }
                            });


                }
            });
        }
    }


    /**
     * 在底部弹出评论的评论
     */
    private void showBottomSheetListDialog(SuperCommentBean superComment) {

        dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.replay_comments, null);
        RecyclerView recyclerView = view.findViewById(R.id.replay_recyclerview);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(manager);
        sonAdapter = new SonCommentsAdapter();
        recyclerView.setAdapter(sonAdapter);
        sonAdapter.setList(null);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        ((TextView) view.findViewById(R.id.replay_nums)).setText("回复");
        // 点击箭头关闭BottomSheetDialog
        ((ImageButton) view.findViewById(R.id.replay_back_btn)).setOnClickListener(v -> dialog.cancel());

        ((TextView) view.findViewById(R.id.comment_item_username)).setText(superComment.getUserName());
        ((TextView) view.findViewById(R.id.comment_item_time)).setText(DateUtils.millis2String(Long.parseLong(superComment.getCommentTime()) , DateUtils.yyyyMMdd.get()));
        ((TextView) view.findViewById(R.id.comment_item_text)).setText(superComment.getCommentText());
        ((TextView) view.findViewById(R.id.comment_item_go_replay)).setVisibility(View.GONE);
        //((TextView) view.findViewById(R.id.comment_item_like_nums)).setText(String.valueOf(superComment.getCommentLikes()));
        ((TextView) view.findViewById(R.id.comment_item_like_nums)).setVisibility(View.INVISIBLE);
        view.findViewById(R.id.comment_item_like_btn).setVisibility(View.INVISIBLE);

        Glide.with(this)
                .load(superComment.getImgUrl())
                .into((ImageView)view.findViewById(R.id.comment_item_avatar));

        // 点击子评论的评论框弹出评论框, 评论父评论
        view.findViewById(R.id.replay_bottom_comment).setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = superComment.getUseId();
        });

        // 上拉加载
        initSonLoadMore(superComment.getCommentId());

        // 点击评论加载更多
        sonAdapter.setOnItemClickListener((adapter1, view1, position) -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = sonAdapter.getData().get(position).getUseId();
        });

        sonAdapter.addChildClickViewIds(R.id.replay_item_like_btn, R.id.replay_item_avatar);
        sonAdapter.setOnItemChildClickListener((adapter1, view1, position) -> {
            if (view1.getId() == R.id.replay_item_like_btn) {
                // 子评论点赞
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }

                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                itemView.findViewById(R.id.replay_item_like_btn).setClickable(false);

                //ShineButton shineButton = (ShineButton) view;
                SonCommentBean sonComment = sonAdapter.getItem(position);
                //未点赞，点赞请求
                if (sonComment.getIsLike().equals(0)) {
                    Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(1);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() + 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });

                        }
                    });
                } else {
                    Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(0);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() - 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });
                        }
                    });
                }
            } else if (view1.getId() == R.id.replay_item_avatar) {
                Intent intent = new Intent(DynamicDetailActivity.this, OtherUserDetailActivity.class);
                intent.putExtra("id", sonAdapter.getItem(position).getUseId());
                startActivity(intent);
            }
        });

        // 子评论长按删除
        sonAdapter.setOnItemLongClickListener((adapter1, view1, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!sonAdapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(2, position));
            showBottomDialog();

            return false;
        });


    }

    /**
     * 上拉加载更多评论
     */
    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    /**
     * 子评论上拉加载更多
     */
    private void initSonLoadMore(int superId) {
        sonAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                sonRequest(superId);
            }
        });
        sonAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        sonAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void request() {
        mViewModel.getSuperComments(ReplayType.DYNAMIC, dynamicId, superCommentsPage.getPage());
    }

    private void sonRequest(int superId) {
        mViewModel.getSonComments(superId, sonPageInfo.getPage());
    }

    /**
     * 初始化九宫格布局适配器
     */
    private void initNineGridAdapter() {
        nineGridAdapter = new NineGridAdapter();
        dynamicDetailNglImages.setAdapter(nineGridAdapter);
    }

    private void initData() {
        mViewModel.getDynamicById(dynamicId);
        mViewModel.getPraiseRelationShip(Utils.getUserId(), ReplayType.DYNAMIC, dynamicId);
        mViewModel.getSuperComments(ReplayType.DYNAMIC, dynamicId, superCommentsPage.getPage());

    }

    // 观察者
    private void observe() {

        mViewModel.isCompleteLiveData().observe(this, aBoolean -> {
            if (aBoolean) {
                mMiniLoadingDialog.dismiss();
            }
        });

        mViewModel.getDynamicBeanLiveData().observe(this, dynamicBean -> {
            binding.dynamicDetailUsername.setText(dynamicBean.getUserName());
            binding.dynamicDetailCreateTime.setText(DateUtils.millis2String(Long.parseLong(dynamicBean.getCreateTime()), DateUtils.yyyyMMdd.get()));
            binding.dynamicDetailText.setText(dynamicBean.getDynamicText());
            binding.dynamicDetailReplayNum.setText(String.valueOf(dynamicBean.getComments()));
            binding.dynamicDetailPraiseNum.setText(String.valueOf(dynamicBean.getLikes()));
            Glide.with(this)
                    .load(dynamicBean.getUserUrl())
                    .into(binding.dynamicDetailAvatar);

            List<String> imgList = new ArrayList<>();
            for (String s : dynamicBean.getDynamicUrl()) {
                if (!Utils.isStringEmpty(s)) {
                    imgList.add(s);
                }
            }
            dynamicDetailNglImages.setImagesData(imgList, NineGridImageView.NOSPAN);

            // 获取到动态信息后会得到目的用户id，然后获得关注关系
            mViewModel.getFellowRelationShip(Utils.getUserId(), FellowType.USER, dynamicBean.getUserId());

            // 如果这个动态是自己发的，不显示关注按钮
            if (dynamicBean.getUserId().equals(Utils.getUserId())) {
                binding.dynamicDetailFollow.setVisibility(View.INVISIBLE);
            }

            if (!dynamicBean.getType().equals(DynamicType.ORIGINAL_DYNAMIC)) {
                binding.dynamicDetailNglImages.setVisibility(View.GONE);
                binding.editShare.setVisibility(View.VISIBLE);

                // 基地
                if (dynamicBean.getType().equals(DynamicType.BASE)) {
                    HashMap<String, String> body = new HashMap<>();
                    body.put("id", String.valueOf(dynamicBean.getTypeId()));
                    HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
                    httpUtil.get(Url.GET_BASE_DETAIL, body, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean<BaseDetailBean> resultBean = JsonUtilNew.fromJsonObject(resultStr, BaseDetailBean.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    if (resultBean.getData() == null) {
                                        return;
                                    }
                                    binding.originalUserNameDynamic.setText("@" + resultBean.getData().getTitle());
                                    binding.originalTextDynamic.setText(resultBean.getData().getDescribe());
                                    Glide.with(MyApp.getContext())
                                        .load(resultBean.getData().getBannerImageUrls().get(0))
                                        .into(binding.originalAvatarDynamic);
                                });
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            Utils.SoutErr(e.getMessage());
                        }
                    });

                } else if (dynamicBean.getType().equals(DynamicType.DYNAMIC)) {
                    Network.getDynamicById(dynamicBean.getTypeId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean<DynamicBean> resultBean = JsonUtilNew.fromJsonObject(resultStr, DynamicBean.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    if (resultBean.getData() == null) {
                                        return;
                                    }
                                    binding.originalUserNameDynamic.setText("@" + resultBean.getData().getUserName());
                                    binding.originalTextDynamic.setText(resultBean.getData().getDynamicText());
                                    Glide.with(MyApp.getContext())
                                            .load(resultBean.getData().getDynamicUrl().get(0))
                                            .into(binding.originalAvatarDynamic);
                                });
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {

                        }
                    });
                } else if (dynamicBean.getType().equals(DynamicType.TRAVEL)) {
                    Network.loadTravelDetail(dynamicBean.getTypeId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean<TravelDetailBean> resultBean = JsonUtilNew.fromJsonObject(resultStr, TravelDetailBean.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    if (resultBean.getData() == null) {
                                        return;
                                    }
                                    binding.originalUserNameDynamic.setText("@" + resultBean.getData().getTitle());
                                    StringBuilder stringBuilder = new StringBuilder();
                                    resultBean.getData().getContent().forEach(subTravelBean -> {
                                        stringBuilder.append(subTravelBean.getText());
                                    });

                                    binding.originalTextDynamic.setText(RichUtils.returnOnlyText(stringBuilder.toString()));
                                    Glide.with(MyApp.getContext())
                                            .load(RichUtils.returnImageUrlsFromHtml(stringBuilder.toString()).get(0))
                                            .into(binding.originalAvatarDynamic);
                                });
                            } else {
                                failed(new IOException(resultBean.getMsg()));
                            }
                        }

                        @Override
                        public void failed(IOException e) {

                        }
                    });
                }
            }



        });

        mViewModel.getIsPraiseLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                binding.dynamicDetailPraiseNum.setTextColor(Color.parseColor("#E54D42"));
                binding.dynamicDetailPraiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_red_20);
            } else {
                binding.dynamicDetailPraiseNum.setTextColor(Color.parseColor("#8A000000"));
                binding.dynamicDetailPraiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_gray_24);
            }
        });

        mViewModel.getIsFellowLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                binding.dynamicDetailFollow.setText("已关注");
                binding.dynamicDetailFollow.setBackgroundResource(R.drawable.btn_attentioned);
            }else {
                binding.dynamicDetailFollow.setText("关注");
                binding.dynamicDetailFollow.setBackgroundResource(R.drawable.btn_un_attentioned);
            }
        });

        mViewModel.getSuperCommentsLiveData().observe(this, superCommentBeans -> {
            if (superCommentsPage.isFirstPage()) {
                adapter.setList(superCommentBeans);
                if (isNeedComment) {
                    scrollToEnd();
                    isNeedComment = false;
                }



            } else {
                adapter.addData(superCommentBeans);
            }

            if (superCommentBeans.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                superCommentsPage.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
        });

        mViewModel.getSonCommentsLiveData().observe(this, sonCommentBeans -> {
            if (sonPageInfo.isFirstPage()) {
                sonAdapter.setList(sonCommentBeans);
            } else {
                sonAdapter.addData(sonCommentBeans);
            }

            if (sonCommentBeans.size() < PageInfo.MAX_ITEM) {
                sonAdapter.getLoadMoreModule().loadMoreEnd();
            } else {
                sonPageInfo.nextPage();
                // 加载完成，等待下一次加载
                sonAdapter.getLoadMoreModule().loadMoreComplete();
            }


        });

        // 一级评论被评论数量变化
        mViewModel.getSonCommentChangePositionLiveData().observe(this, integerIntegerPair -> {

            Utils.Sout( "pair---------" + integerIntegerPair.toString());

            if (integerIntegerPair == null || integerIntegerPair.first.equals(-1) || integerIntegerPair.second.equals(Integer.MIN_VALUE)) {
                return;
            }else {
                SuperCommentBean superComment = adapter.getItem(integerIntegerPair.first);
                superComment.setReplyNums(superComment.getReplyNums() + integerIntegerPair.second);
                adapter.setData(integerIntegerPair.first, superComment);
                adapter.notifyItemChanged(integerIntegerPair.first);
                mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(integerIntegerPair.first, Integer.MIN_VALUE));
            }

        });
    }

    /**
     * 评论适配器，使用基地详情页的adapter
     */
    private void initCommentAdapter() {
        adapter = new CommentsAdapter();
        adapter.setAnimationEnable(true);
        binding.dynamicCommentsRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.dynamicCommentsRecyclerview.setAdapter(adapter);
        adapter.setList(null);
    }

    /**
     * 查找信息
     * @param list 图片集合
     */
    private List<ImageViewInfo> computeBoundsBackward(List<String> list) {
        List<ImageViewInfo> res = new ArrayList<>();
        for (int i = 0;i < dynamicDetailNglImages.getChildCount(); i++) {
            View itemView = dynamicDetailNglImages.getChildAt(i);
            ImageView thumbView = (ImageView) itemView;
            if (thumbView.getTag() == null || !thumbView.getTag().equals("load_success")) {
                continue;
            }

            Rect bounds = new Rect();
            if (itemView != null) {
                thumbView.getGlobalVisibleRect(bounds);
                //thumbView.getDrawable() ==
            }
            ImageViewInfo info = new ImageViewInfo(list.get(i));
            info.setBounds(bounds);
            res.add(info);
        }
        return res;
    }

    // 滚动到最底部
    private void scrollToEnd() {
        binding.nestedScrollView.post(() -> {
            binding.nestedScrollView.fullScroll(View.FOCUS_DOWN);//滚到底部
        });
    }

    @Override
    protected void onPause() {

        super.onPause();
    }

    @Override
    protected void onDestroy() {

        if (mViewModel.getIsPraiseLiveData().getValue() != null) {
            sendLiveEvent(mViewModel.getIsPraiseLiveData().getValue());
        }
        mMiniLoadingDialog.recycle();

        mLoadingHandler.removeCallbacksAndMessages(null);

        super.onDestroy();
    }
}